package com.zhang.common.batch.controller;

import com.google.common.collect.Maps;
import com.zhang.common.constant.ErrorMessage;
import com.zhang.common.dto.BaseResponse;
import com.zhang.common.util.DateUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

/**
 * 任务调度WEB
 * <p>
 * 数据库需定义任务名
 *
 * @author zhangshuaiyin
 * @date 2021-08-03
 */
@RestController
@RequestMapping("job")
public class JobController {
    private static final Logger logger = LoggerFactory.getLogger(JobController.class);
    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private JobRegistry jobRegistry;

    @ApiOperation(value = "任务执行", notes = "任务执行")
    @ApiImplicitParam(name = "jobName", value = "job名称", required = true, dataType = "String")
    @RequestMapping("/{jobName}")
    public BaseResponse<Map<String, String>> launcher(
            @PathVariable @ApiParam(name = "jobName", value = "job名称", required = true) String jobName,
            HttpServletRequest request) {
        try {
            JobParameters jobParameters = bulidParameters(request);
            JobExecution result = jobLauncher.run(jobRegistry.getJob(jobName),
                    jobParameters);
            BaseResponse<Map<String, String>> response = BaseResponse.of(ErrorMessage.SUCCESS);
            Map<String, String> map = Maps.newHashMap();
            map.put("jobId", String.valueOf(result.getJobId()));
            map.put("jobName", result.getJobInstance().getJobName());
            map.put("batchStatus", result.getStatus().name());
            map.put("exitCode", result.getExitStatus().getExitCode());
            map.put("exitMessage", result.getExitStatus().getExitDescription());
            map.put("startTime", DateUtils.format(result.getStartTime(), null));
            map.put("endTime", DateUtils.format(result.getEndTime(), null));
            response.setData(map);
            return response;
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e);
            return BaseResponse.of(ErrorMessage.SYSTEM_ERROR);
        }
    }

    /**
     * jobName
     */
    private static final String JOB_NAME = "jobName";

    /**
     * 拼装参数
     *
     * @param request
     * @return
     */
    private JobParameters bulidParameters(HttpServletRequest request) {
        JobParametersBuilder builder = new JobParametersBuilder();

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            if (!JOB_NAME.equals(paramName)) {
                builder.addString(paramName, request.getParameter(paramName));
            }
        }
        builder.addDate("businessDate", new Date());
        return builder.toJobParameters();
    }
}
